package org.Tools;

import java.awt.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//字符串操作
public class StringOP {
    public int row = 0;


    public StringOP() {

    }

    //数据,测量字符串宽度工具,每行文本的长度
    public String LabelStr(String msg,FontMetrics fm,int width) {
        row = 0;

        //字符串长度
        int len = msg.length();
        //指向字符串的指针
        int pt = 0;

        //处理后的字符串
        String Pmsg = "<html>";

        //处理字体换行
        while(pt<len) {
            String str = "";
            while(pt<len) {
                if(msg.charAt(pt)=='\n') {
                    pt++;
                    break;
                }
                str+= msg.charAt(pt);
                pt++;
                if(fm.stringWidth(str)>width) break;
            }
            Pmsg+=str+"<br>";
            row++;
            System.out.println(row);
            System.out.println(str);
        }

        if(row==0) row=1;
        Pmsg+="</html>";    //加上结尾标识

        return Pmsg;
    }

    //将服务器端传来的数据转为json格式
    public String JsonStr(String msg) {
        String originalJson = msg;
        // 匹配对象属性部分，例如Post(postId=1, userId=2,...
        Pattern objectPattern = Pattern.compile("Post\\((.*?)\\)");
        Matcher matcher = objectPattern.matcher(originalJson);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String objectProperties = matcher.group(1);
            // 将属性部分按照=分割，并用双引号包裹属性名和属性值（如果是字符串类型）
            String[] propertyPairs = objectProperties.split(",");
            String newObjectProperties = "";
            for (String pair : propertyPairs) {
                String[] keyValue = pair.trim().split("=");
                if (keyValue.length == 2) {
                    String key = keyValue[0].trim();
                    String value = keyValue[1].trim();
                    if (value.matches("^\\d+$")) {
                        // 如果是数字，直接添加双引号包裹的键值对
                        newObjectProperties += "\"" + key + "\":" + value + ",";
                    } else {
                        // 如果是字符串，添加双引号包裹的键值对，并且对字符串值也用双引号包裹
                        newObjectProperties += "\"" + key + "\":\"" + value + "\",";
                    }
                }
            }
            // 去掉最后多余的逗号
            if (newObjectProperties.length() > 0) {
                newObjectProperties = newObjectProperties.substring(0, newObjectProperties.length() - 1);
            }
            // 替换匹配到的部分为新的符合标准JSON格式的对象部分
            matcher.appendReplacement(sb, "{" + newObjectProperties + "}");
        }
        matcher.appendTail(sb);
        System.out.println(sb.toString());
        return sb.toString();
    }
}
